<script setup>
    import {
        Management,
        Promotion,
        UserFilled,
        User,
        Setting,
        EditPen,
        SwitchButton,
        CaretBottom,
        Avatar,
        Stamp,
        Plus
    } from '@element-plus/icons-vue'
    import avatar from '@/assets/default.png'

    import {ElMessage, ElMessageBox} from 'element-plus'
    import {useRouter} from 'vue-router'

    const router = useRouter();
    import {useTokenStore} from "@/store/token.js";
    import userApi from "@/api/user.js";

    const tokenStore = useTokenStore();
    import {useUserInfoStore} from "@/store/userInfo.js";
    import {ref, reactive} from "vue";

    import authApi from "@/api/auth.js";

    const userInfoStore = useUserInfoStore();

    const titleName = "医院费用管理系统"

    //下拉框
    const genders = [
        {
            id: '男',
            name: '男',
        },
        {
            id: '女',
            name: '女',
        }
    ]

    //条目被点击后,调用的函数
    const handleCommand = (command) => {
        //判断指令
        if (command === 'logout') {
            //退出登录
            tokenStore.removeToken();
            userInfoStore.removeUserInfo();
            //跳转到登录
            router.push('/login')
        } else if (command === 'updateUserInfo'){
            dialogUpdateUserInfoVisible.value = true
            //user.value = userInfoStore.user;
            Object.assign(user.value, userInfoStore.user)
        } else if (command ==='updateAvatar'){
            dialogUpdateAvatarVisible.value = true
            Object.assign(user.value, userInfoStore.user)
        } else if (command === 'resetPassword') {
            dialogResetPasswordVisible.value = true
            userPassword.value = {}
        } else {
            //路由
            router.push('/user/' + command)
        }
    }

    const getUserInfo = () => {
        userApi.userInfo().then(result => {
            if (result.code === 0) {
                userInfoStore.setUserInfo(result.data)
            }
        })
    }
    getUserInfo()

    //修改个人信息
    const dialogUpdateUserInfoVisible = ref(false)
    const user = ref({})

    const headers = ref({
        //添加token
        Authorization: tokenStore.token
    })

    const handleAvatarSuccess = (result) => {
        user.value.image = result.data
    }

    const updateUserInfo = () => {
        userApi.update(user.value).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                dialogUpdateUserInfoVisible.value = false
                //重新加载最新数据
                getUserInfo()
            } else {
                ElMessage.error(result.msg)
            }
        })
    }

    //修改头像
    const dialogUpdateAvatarVisible = ref(false)
    const updateAvatar = () => {
        userApi.update(user.value).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                dialogUpdateAvatarVisible.value = false
                //重新加载最新数据
                getUserInfo()
            } else {
                ElMessage.error(result.msg)
            }
        })
    }

    //重置密码
    const dialogResetPasswordVisible = ref(false)
    const userPassword = ref({})
    const resetFormRef = ref()
    const rePasswordValid = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请重新输入密码'))
        } else if (value !== userPassword.value.newPassword) {
            callback(new Error('两次输入新密码不一致'))
        } else {
            callback()
        }
    }

    //表单正则表达式
    const rules = ref({
        oldPassword: [
            {required: true, message:'请输入旧密码', trigger:"blur"},
            {min: 6, max: 16, message: '用户名长度必须为6~16位', trigger:"blur"},
        ],
        newPassword: [
            {required: true, message: '请输入新密码', trigger:"blur"},
            {min: 6, max: 16, message: '密码长度必须为6~16位', trigger:"blur"},
        ],
        reNewPassword: [
            {required: true, message: '请再次输入新密码', trigger:"blur"},
            {validator: rePasswordValid, trigger:"blur"},
        ]
    })

    const resetPassword = (formEl) => {
        if (!formEl) return
        formEl.validate((valid) => {
            if (valid) {
                userApi.resetPassword(userPassword.value).then(result => {
                    if (result.code === 0) {
                        ElMessage({message: result.msg, type: 'success',})
                        dialogResetPasswordVisible.value = false
                        //退出登录
                        tokenStore.removeToken()
                        userInfoStore.removeUserInfo()
                        //跳转到登录界面
                        router.push('/login')
                    } else {
                        ElMessage.error(result.msg)
                    }
                })
            } else {
                ElMessage.error('表单验证失败')
            }
        })
    }

    //获取权限路径
    const authList = ref({})
    const getAuthList = () => {
        authApi.selectByRole().then(result => {
            authList.value = result.data
        })
    }
    getAuthList()
</script>

<template>
    <!-- element-plus中的容器 -->
    <el-container class="layout-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
            <div class="el-aside__logo"></div>
            <!-- element-plus的菜单标签 -->
            <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
                     router>
                <div v-for="auth in authList">
                    <el-menu-item  :index="auth.path">
                        <el-icon>
                            <Management/>
                        </el-icon>
                        <span>{{auth.name}}</span>
                    </el-menu-item>
                </div>

                <!--<el-menu-item index="/user">
                    <el-icon>
                        <User/>
                    </el-icon>
                    <span>用户管理</span>
                </el-menu-item>
                <el-menu-item index="/patient">
                    <el-icon>
                        <EditPen/>
                    </el-icon>
                    <span>患者管理</span>
                </el-menu-item>
                <el-menu-item index="/medicine">
                    <el-icon>
                        <EditPen/>
                    </el-icon>
                    <span>药品管理</span>
                </el-menu-item>
                <el-menu-item index="/auth">
                    <el-icon>
                        <Promotion/>
                    </el-icon>
                    <span>权限管理</span>
                </el-menu-item>
                <el-menu-item index="/department">
                    <el-icon>
                        <Promotion/>
                    </el-icon>
                    <span>科室管理</span>
                </el-menu-item>
                <el-menu-item index="/category">
                    <el-icon>
                        <Promotion/>
                    </el-icon>
                    <span>药品类型管理</span>
                </el-menu-item>
                <el-menu-item index="/restocking">
                    <el-icon>
                        <Management/>
                    </el-icon>
                    <span>药品进货管理</span>
                </el-menu-item>
                <el-menu-item index="/order">
                    <el-icon>
                        <Management/>
                    </el-icon>
                    <span>药品售卖管理</span>
                </el-menu-item>
                <el-menu-item index="/echarts">
                    <el-icon>
                        <Management/>
                    </el-icon>
                    <span>统计图表</span>
                </el-menu-item>-->

                <el-sub-menu>
                    <template #title>
                        <el-icon>
                            <Setting/>
                        </el-icon>
                        <span>个人中心</span>
                    </template>
                    <el-menu-item index="/userInfo">
                        <el-icon>
                            <UserFilled/>
                        </el-icon>
                        <span>基本资料</span>
                    </el-menu-item>
                    <el-menu-item index="/userAvatar">
                        <el-icon>
                            <Avatar/>
                        </el-icon>
                        <span>更换头像</span>
                    </el-menu-item>
                    <el-menu-item index="/userResetPassword">
                        <el-icon>
                            <Stamp/>
                        </el-icon>
                        <span>重置密码</span>
                    </el-menu-item>
                </el-sub-menu>
            </el-menu>
        </el-aside>
        <!-- 右侧主区域 -->
        <el-container>
            <!-- 头部区域 -->
            <el-header>
                <div><strong>{{titleName}}</strong></div>
                <div class="el-header">
                    <strong>Hi!{{userInfoStore.user.name}}&nbsp&nbsp</strong>
                    <!-- 下拉菜单 -->
                    <!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
                    <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                        <el-avatar :src="userInfoStore.user.image?userInfoStore.user.image:avatar"/>
                        <el-icon>
                            <CaretBottom/>
                        </el-icon>
                    </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="updateUserInfo" :icon="UserFilled">基本资料</el-dropdown-item>
                                <el-dropdown-item command="updateAvatar" :icon="Avatar">更换头像</el-dropdown-item>
                                <el-dropdown-item command="resetPassword" :icon="Stamp">重置密码</el-dropdown-item>
                                <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </el-header>
            <!-- 中间区域 -->
            <el-main>
                <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
                    内容展示区
                </div> -->
                <router-view></router-view>
            </el-main>
            <!-- 底部区域 -->
            <el-footer>后台管理 ©2024 Created by ckx</el-footer>
        </el-container>
    </el-container>

    <el-dialog v-model="dialogUpdateUserInfoVisible" title="修改基本资料" width="500" :lock-scroll="false">
        <el-form :model="user">
            <el-form-item label="姓名" :label-width="60">
                <el-input v-model="user.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="年龄" :label-width="60">
                <el-input v-model="user.age" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别" :label-width="60">
                <el-select v-model="user.gender" clearable placeholder="请选择性别">
                    <el-option
                        v-for="gender in genders"
                        :key="gender.id"
                        :label="gender.name"
                        :value="gender.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="头像" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers"
                >
                    <img v-if="user.image" :src="user.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogUpdateUserInfoVisible  = false">取消</el-button>
                <el-button type="primary" @click="updateUserInfo">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogUpdateAvatarVisible" title="修改头像" width="500" :lock-scroll="false">
        <el-form :model="user">
            <el-form-item label="头像" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers"
                >
                    <img v-if="user.image" :src="user.image" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogUpdateAvatarVisible  = false">取消</el-button>
                <el-button type="primary" @click="updateAvatar">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogResetPasswordVisible" title="修改密码" width="500" :lock-scroll="false">
        <el-form ref="resetFormRef" :rules="rules" :model="userPassword">
            <el-form-item prop="oldPassword" label="原密码" :label-width="100">
                <el-input v-model="userPassword.oldPassword" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="newPassword" label="新密码" :label-width="100">
                <el-input v-model="userPassword.newPassword" autocomplete="off"/>
            </el-form-item>
            <el-form-item prop="reNewPassword" label="重复新密码" :label-width="100">
                <el-input v-model="userPassword.reNewPassword" autocomplete="off"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogResetPasswordVisible = false">取消</el-button>
                <el-button type="primary" @click="resetPassword(resetFormRef)">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .layout-container {
        height: 100vh;

        .el-aside {
            background-color: #232323;

            &__logo {
                height: 120px;
                background: url('@/assets/logo.png') no-repeat center / 120px auto;
            }

            .el-menu {
                border-right: none;
            }
        }

        .el-header {
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .el-dropdown__box {
                display: flex;
                align-items: center;

                .el-icon {
                    color: #999;
                    margin-left: 10px;
                }

                &:active,
                &:focus {
                    outline: none;
                }
            }
        }

        .el-footer {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #666;
        }
    }
</style>